<?php
    /**
     * Created by PhpStorm.
     * User: mybook-lhp
     * Date: 18/6/5
     * Time: 下午4:35
     */

    namespace app\store\api;


    use app\common\controller\API;
    use app\store\model\CartModel;
    use app\store\model\GoodsModel;
    use think\Db;

    class Cart extends API
    {

        /**
         * 添加到购物车
         * api POST /store/cart/add
         *
         * @param int $goods_id  商品ID
         * @param int $goods_num 商品数量
         *
         * @return integer $code 200成功-500失败
         */
        public function add()
        {

            $param = $this->request->param();
            $this->check_validate($param,'Cart.save');

            $goods_images = GoodsModel::whereIn('id',$param['goods_id'])->where(['status' => 1])->column('id,image,name,price,point,company');

            if ($goods_images)
            {
                $goods_images = $goods_images[$param['goods_id']];
                $update       = CartModel::where([
                    'buyer_id' => $this->member_id,
                    'goods_id' => $param['goods_id']
                ])->find();
                if ($update)
                {
                    $update->goods_num = $update->goods_num + $param['goods_num'];
                    $rest              = $update->save();
                }
                else
                {
                    $data['buyer_id']      = $this->member_id;
                    $data['goods_id']      = $param['goods_id'];
                    $data['goods_num']     = $param['goods_num'];
                    $data['goods_name']    = $goods_images['name'];
                    $data['goods_price']   = $goods_images['price'];
                    $data['goods_image']   = $goods_images['image'];
                    $data['point']         = $goods_images['point'];
                    $data['goods_company'] = $goods_images['company'];

                    $rest = CartModel::create($data);
                }
            }
            else
            {
                $this->error('商品部存在或已下架！','');
            }

            $rest ? $this->success('添加成功') : $this->error('添加失败！','');

        }

        /**
         * 购物车列表
         * api POST /store/cart/lists
         *
         * @return array $data
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         */
        public function lists()
        {

            $cart = CartModel::where(['buyer_id' => $this->member_id])->select();
            if ($cart)
            {
                $module_config = module_config('store');
                foreach ($cart as &$item)
                {
                    if (isset($item['goods_image']) && $item['goods_image'] !== '')
                    {
                        $item['goods_image'] = get_file_path($item['goods_image']);
                    }

                    if ($module_config['store_price_view'] == GoodsModel::PRICE_VIEW_NOTHING)
                    {
                        unset($item['price'],$item['point']);
                        $item['company_title'] = ' ';
                    }
                    if ($module_config['store_price_view'] == GoodsModel::PRICE_VIEW_POINT)
                    {
                        unset($item['price']);
                        $item['company_title'] = $item['point'] . ' 积分/' . $item['goods_company'];
                    }
                    if ($module_config['store_price_view'] == GoodsModel::PRICE_VIEW_PRICE)
                    {
                        unset($item['point']);
                        $item['company_title'] = $item['price'] . ' 元/' . $item['goods_company'];
                    }

                }
                unset($item);
            }
            $this->result($cart);
        }

        /**
         * 购物车数量
         * api POST /store/cart/cartnum
         *
         * @return array $data
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         */
        public function cartnum()
        {

            $cart = CartModel::where(['buyer_id' => $this->member_id])->count();

            $this->result($cart);


        }

        /**
         * 更新购物车
         * api POST /store/cart/update
         *
         * @param integer $goods_id  商品ID
         * @param integer $goods_num 商品数量
         *
         * @return string $code    200-成功500-失败
         */
        public function update()
        {

            $param = $this->request->param();

            $re = CartModel::update(['goods_num' => $param['goods_num']],[
                'buyer_id' => $this->member_id,
                'goods_id' => $param['goods_id']
            ]);
            if ($re)
            {
                $this->success('更新成功！');
            }
            else
            {
                $this->error('更新失败');
            }
        }

        /**
         * 删除购物车
         * api POST /store/cart/del
         *
         * @param  integer $ids 购物车ID，逗号分隔-例如：1，2，3，4
         *
         * @return string $code  200-成功500-失败
         * @return string $msg  错误说明
         * @return string $data[]
         */
        public function del()
        {

            $param = $this->request->param();
            if (isset($param['ids']))
            {
                if (CartModel::whereIn('id',$param['ids'])->delete())
                {
                    $this->success('删除成功！');
                }
                else
                {
                    $this->error('删除失败');
                }

            }
            else
            {
                $this->error('参数错误！');
            }
        }

        /**
         * 购物车下单
         * api POST /store/cart/toorder
         *
         * @param  integer $cart_ids 购物车ID，逗号分隔-例如：1，2，3，4
         *
         * @return $this|array
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         */
        public function toorder()
        {

            $cart_ids = $this->request->param('cart_ids');

            $cart_goods = Db::name('store_cart')->whereIn('id',$cart_ids)->select();

            if (empty($cart_goods))
            {
                $this->error('购物车已经被清空了!');
            }

            $cart_goods_ = [];
            foreach ($cart_goods as $cart_good)
            {
                $cart_goods_[$cart_good['seller_id']][] = $cart_good;
            }
            unset($cart_goods);

            foreach ($cart_goods_ as $key => $item)
            {

                foreach ($item as $keys => $cart_good)
                {
                    $GoodsInfo = Db::name('store')->where('goods_id',$cart_good['goods_id'])->find();
                    //dump([$cart_good['goods_id'],$GoodsInfo,Db::name('store')->getLastSql()]);
                    $OrderGoods0['goods_id']    = $cart_good['goods_id'];
                    $OrderGoods0['seller_id']   = $GoodsInfo['member_id'];
                    $OrderGoods0['seller_name'] = $GoodsInfo['member_name'];;
                    $OrderGoods0['goods_price']  = $GoodsInfo['goods_store_price'];
                    $OrderGoods0['goods_num']    = $cart_good['goods_num'];
                    $OrderGoods0['goods_image']  = get_file_path($cart_good['goods_image'],$OrderGoods0['seller_id']);
                    $OrderGoods0['goods_name']   = $GoodsInfo['goods_name'];
                    $OrderGoods0['goods_amount'] = $OrderGoods0['goods_price'] * $cart_good['goods_num'];
                    $order_goods[$key][$keys]    = $OrderGoods0;
                }
            }

            $this->result(empty($order_goods) ? [] : array_values($order_goods));
        }

    }